package novel

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/flipped-aurora/gin-vue-admin/server/model/novel"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gocolly/colly"
	"net/http"
	"strings"
	"time"
)

type Novel interface {

	// ChapterByAuthorAndName 通过作者 和 书名获取章节
	ChapterByAuthorAndName(author string, name string, id string) (*novel.BookChapters, error)

	// 通过书名搜索
	SearchByName(name string) ([]novel.BillBook, error)

	// 获取小说详情
	DetailById(id string) (*novel.BookDetail, error)
	// 获取小说内容
	ContentByUrl(urlStr string) (*novel.ChapterInfo, error)

	// 通过id 获取小说章节
	ChapterByAuthorById(id string) (*novel.BookChapters, error)

	// 下载小说
	DownloadByUrl(url string)
}

const (
	EmptyContentChapter = "/novel/content/-1"
	EmptyChapterContent = "没有当前小说数据,可联系微信:gylangisme"
)

var EmptyChapterList = []novel.BookChapter{{Title: "无章节信息", Link: EmptyContentChapter, Unreadble: "false"}}

func CreateCollector() *colly.Collector {
	collector := colly.NewCollector()
	rule := &colly.LimitRule{
		RandomDelay: time.Second,
		Parallelism: 1, //并发数为10
	}
	_ = collector.Limit(rule)
	return collector
}

func GetDocument(method string, url string, data string, header http.Header) (*goquery.Document, error) {
	collector := CreateCollector()
	var html *goquery.Document
	collector.OnResponse(func(response *colly.Response) {
		s := string(response.Body)
		html, _ = goquery.NewDocumentFromReader(strings.NewReader(s))
	})

	err := collector.Request(method, url, utils.Str2ReadCloser(data), nil, header)
	if nil != err {
		return nil, err
	}
	// 解析
	if nil == html {
		return nil, fmt.Errorf("获取图书失败, 请联系管理员错误码:8665896")
	}
	return html, err
}
func ParseTDate(date time.Time) string {

	return date.Format("2006-01-02T15:04:05")
}
